package com.hlc.helloWord.common.token;

import com.alibaba.fastjson.JSON;
import com.hlc.helloWord.common.exception.MyException;
import com.hlc.helloWord.common.redis.RedisUtil;
import com.hlc.helloWord.common.result.ResultEnum;
import com.hlc.helloWord.user.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.UnsupportedEncodingException;
import java.util.UUID;

/**
 * Created by helinchong on 2017/12/26.
 */
@Service
public class TokenUtil {

    @Autowired
    private RedisUtil redisUtil;
    /**
     * 生成token并保存
     * @param user
     * @return
     */
    public boolean setToken(User user){
        if(user==null){
            throw new MyException(ResultEnum.ERROR.getCode(),"user_is_null!");
        }
        //生成token
        user.setToken(generateToken(user.getId()));
        redisUtil.set(Token.token + user.getId(),JSON.toJSONString(user),60*20);
        return true;
    }

    /**
     * 验证token
     * @param token
     * @return
     */
    public boolean checkToken(String token){
        if(token == null || "".equals(token)){
            throw new MyException(ResultEnum.ERROR.getCode(),"token为空!");
        }
        String baseToken = getFromBase64(token);
        String key = baseToken.substring(baseToken.lastIndexOf("_") + 1);
        //到redis中取值
        String loginUserJson = redisUtil.get(Token.token + key).toString();
        if(loginUserJson != null){
            User user = JSON.parseObject(loginUserJson, User.class);
            //比较token
            if(!user.getToken().equals(token)){
                throw new MyException(ResultEnum.RELOGIN.getCode(),"你的账号在别处登录!");
            }
            redisUtil.expire(Token.token + key,60*20);
        }else{
            throw new MyException(ResultEnum.RELOGIN.getCode(),"需要登录!");
        }
        return true;
    }

    public void delToken(Integer userId){
        redisUtil.del(Token.token + userId);
    }

    /**
     * 生成token
     * @param userId
     * @return
     */
    public String generateToken(Integer userId){
        return getBase64(Token.token + UUID.randomUUID().toString()+ "_" + userId);
    }


    // 加密
    public String getBase64(String str) {
        byte[] b = null;
        String s = null;
        try {
            b = str.getBytes("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (b != null) {
            s = new BASE64Encoder().encode(b);
        }
        return s;
    }

    // 解密
    public String getFromBase64(String s) {
        byte[] b = null;
        String result = null;
        if (s != null) {
            BASE64Decoder decoder = new BASE64Decoder();
            try {
                b = decoder.decodeBuffer(s);
                result = new String(b, "utf-8");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}
